/*
 *  Common CPU TLB handling
 *
 *  Copyright (c) 2003 Fabrice Bellard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"
#include "cpu.h"
#include "exec/exec-all.h"
#include "exec/memory.h"
#include "exec/address-spaces.h"

#include "exec/cputlb.h"

#include "exec/memory-internal.h"

//#define DEBUG_TLB
//#define DEBUG_TLB_CHECK

/* statistics */
int tlb_flush_count;

#ifdef X86_TLB_ACOUNT
static const CPUTLBEntry s_cputlb_empty_entry = {
    .addr_read  = -1,
    .addr_write = -1,
    .addr_code  = -1,
    .addend     = -1,
};
#else
static const CPUTLBEntry s_cputlb_empty_entry = {
    .addr_read  = -1,
    .addr_write = -1,
    .addr_code  = -1,
    .addend     = -1,
};
#endif

static bool is_empty_tlb(CPUTLBEntry *te) 
{
   return te->addr_read  == s_cputlb_empty_entry.addr_read  &&
          te->addr_write == s_cputlb_empty_entry.addr_write &&
          te->addr_code  == s_cputlb_empty_entry.addr_code;
}

void copy_tlb(CPUTLBEntry *te, CPUTLBEntry *se, hwaddr *iote, hwaddr *iose) 
{
   te->addr_read  = se->addr_read;
   te->addr_write = se->addr_write;
   te->addr_code  = se->addr_code;
   te->addend     = se->addend;
   *iote          = *iose;

#ifdef X86_TLB_ACOUNT
    CPUTLBStatsEntry *tes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(te);
    CPUTLBStatsEntry *ses = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(se);
    tes->acount = ses->acount;
#endif
}

void swap_tlb(CPUTLBEntry *te, CPUTLBEntry *se, hwaddr *iote, hwaddr *iose) 
{
   /* swap tlb entry */
   CPUTLBEntry tmp;
   tmp.addr_read  = te->addr_read;
   tmp.addr_write = te->addr_write;
   tmp.addr_code  = te->addr_code;
   tmp.addend     = te->addend;

   te->addr_read  = se->addr_read;
   te->addr_write = se->addr_write;
   te->addr_code  = se->addr_code;
   te->addend     = se->addend;

   se->addr_read  = tmp.addr_read;
   se->addr_write = tmp.addr_write;
   se->addr_code  = tmp.addr_code;
   se->addend     = tmp.addend;

   /* swap io tlb entry */
   hwaddr iotmp;
   iotmp = *iose;
   *iose = *iote;
   *iote = iotmp;

#ifdef X86_TLB_ACOUNT
    CPUTLBStatsEntry *tes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(te);
    CPUTLBStatsEntry *ses = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(se);
    target_ulong tmp_acount = tes->acount;
    tes->acount = ses->acount;
    ses->acount = tmp_acount;
#endif
}

#ifdef X86_TLB_ACOUNT
#define ACOUNT_LESS(X, Y)  (X->acount < Y->acount)
#else
#define ACOUNT_LESS(X, Y)  0 
#endif
static void reorder_tlb(CPUArchState *env, unsigned mmu_idx, unsigned index)
{
    CPUTLBEntry *pte = &env->tlb_z_set[mmu_idx][index];
    CPUTLBEntry *ste = &env->tlb_o_set[mmu_idx][index];
    CPUTLBEntry *tte = &env->tlb_t_set[mmu_idx][index];
    CPUTLBEntry *fte = &env->tlb_f_set[mmu_idx][index];
    hwaddr      *pti = &env->iotlb_z_set[mmu_idx][index];
    hwaddr      *sti = &env->iotlb_o_set[mmu_idx][index];
    hwaddr      *tti = &env->iotlb_t_set[mmu_idx][index];
    hwaddr      *fti = &env->iotlb_f_set[mmu_idx][index];
    CPUTLBStatsEntry *ptes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(pte);
    CPUTLBStatsEntry *stes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(ste);
    CPUTLBStatsEntry *ttes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(tte);
    CPUTLBStatsEntry *ftes = (CPUTLBStatsEntry*) X86_CPU_GET_TLB_STATS(fte);
    
    /* swap based on frequency */
    if (ACOUNT_LESS(ptes, stes) && env->tlb_xchg++)  swap_tlb(pte,ste,pti,sti);
    if (ACOUNT_LESS(ttes, ftes) && env->tlb_xchg++)  swap_tlb(tte,fte,tti,fti);
}

#ifdef X86_DYNSIZE_TLB
#define TLB_HASH_SIZE 8192 
#define TLB_HASH_SIZE_MO (TLB_HASH_SIZE-1)

/// -------------------------------------------------------- ///
/// Scaling Heurisitics                                      ///
/// we take 2 things into account. 
/// 1. the load of the TLB hash.
/// 2. the # of the conflict misses. 
/// 
/// Expansion.
/// To expand, the tlb hash load must be beyond ESF and the 
/// # of conflict misses must be higher than  

/* expansion and shrinking factor */
static const float esf = 0.70;
static const float ssf = 0.40;
static unsigned hashsize = TLB_HASH_SIZE;
static unsigned hash_tlbsize[TLB_HASH_SIZE] = { [0 ... TLB_HASH_SIZE_MO] = CPU_TLB_INI_SIZE};
static unsigned hash_tlbconm[TLB_HASH_SIZE] = { [0 ... TLB_HASH_SIZE_MO] = 0};
void tlb_resize(CPUArchState *env);
void tlb_reload_size(CPUArchState *env);
#define TLB_MIN(a,b) (((a)<(b))?(a):(b))
#define TLB_MAX(a,b) (((a)>(b))?(a):(b))

static bool tlb_should_expand(CPUArchState *env)
{
   int mmu_idx = 0;
   unsigned hash_idx = env->cr[3] & (hashsize-1);
   unsigned dynsize = hash_tlbsize[hash_idx];

   bool expand = false;
   /* to expand the TLB, only one mode is needed */
   for (;mmu_idx < NB_MMU_MODES; mmu_idx++)
   {
      expand |= (env->tlb_load[mmu_idx] > dynsize*esf);
   }
   /// expand |= (env->tlb_cftm > cmc);
   return expand;
}

static bool tlb_should_shrink(CPUArchState *env)
{
   int mmu_idx = 0;
   unsigned hash_idx = env->cr[3] & (hashsize-1);
   unsigned dynsize = hash_tlbsize[hash_idx];

   bool shrink = true;
   /* to shrink the TLB, all the modes have to agree */
   for (;mmu_idx < NB_MMU_MODES; mmu_idx++)
   {
      shrink &= (env->tlb_load[mmu_idx] < dynsize*ssf);
   }
  /// shrink &= (env->tlb_cftm < cmc);
   return shrink;
}

/* called before CR3 changes */
void tlb_resize(CPUArchState *env)
{
   unsigned hash_idx = env->cr[3] & (hashsize-1);
   /* adjust the tlb dynamic size for the current process */
   if (tlb_should_expand(env)) hash_tlbsize[hash_idx] *= 2;
   if (tlb_should_shrink(env)) hash_tlbsize[hash_idx] /= 2;

   env->tlb_cftm = 0;
}

   static unsigned max = 0; 

/* called after CR3 changes */
void tlb_reload_size(CPUArchState *env)
{
   int mmu_idx = 0;
   env->tlb_size = hash_tlbsize[(env->cr[3] & (hashsize-1))];
   env->tlb_size = TLB_MIN(env->dyn_tlb_size, CPU_TLB_MAX_SIZE);
   env->tlb_size = TLB_MAX(env->dyn_tlb_size, CPU_TLB_MIN_SIZE);
   env->tlb_hash = (CPU_TLB_SIZE_ENV(env) - 1) << CPU_TLB_ENTRY_BITS;
   for (;mmu_idx < NB_MMU_MODES; mmu_idx++) env->tlb_load[mmu_idx] = 0;
   if (env->tlb_size > max) max = env->dyn_tlb_size;
   ///FILE* abc = fopen("/tmp/scale.log", "a+");
   ///fprintf(abc, "env->tlb_size is %d max size is %d\n", env->dyn_tlb_size, max);
   ///fclose(abc);
}
#endif

/* NOTE:
 * If flush_global is true (the usual case), flush all tlb entries.
 * If flush_global is false, flush (at least) all tlb entries not
 * marked global.
 *
 * Since QEMU doesn't currently implement a global/not-global flag
 * for tlb entries, at the moment tlb_flush() will also flush all
 * tlb entries in the flush_global == false case. This is OK because
 * CPU architectures generally permit an implementation to drop
 * entries from the TLB at any time, so flushing more entries than
 * required is only an efficiency issue, not a correctness issue.
 */
__attribute__((optimize("tree-vectorize")))
void tlb_flush(CPUArchState *env, int flush_global)
{
    struct timespec tstart={0,0}, tend={0,0};
    clock_gettime(CLOCK_MONOTONIC, &tstart);

    CPUState *cpu = ENV_GET_CPU(env);
    int i;

#if defined(DEBUG_TLB)
    printf("tlb_flush:\n");
#endif
    /* must reset current TB so that interrupts cannot modify the
       links while we are modifying them */
    cpu->current_tb = NULL;

#ifdef X86_DYNSIZE_TLB
    for (i = 0; i < CPU_TLB_SIZE_ENV(env); i++) {
#else
    for (i = 0; i < CPU_TLB_SIZE; i++) {
#endif
        int mmu_idx;
        for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
#ifdef X86_TLB_PREFETCH
            __builtin_prefetch(&env->tlb_z_set[mmu_idx][i+X86_TLB_PREFD], 1, 0);
#endif
#ifdef X86_TLB_ACOUNT
            ((CPUTLBStatsEntry*) (X86_CPU_GET_TLB_STATS(&env->tlb_z_set[mmu_idx][i])))->acount = 0;
#endif
            env->tlb_z_set[mmu_idx][i] = s_cputlb_empty_entry;

#if X86_TLB_ASSOC >= 2 
#ifdef X86_TLB_PREFTCH
            __builtin_prefetch(&env->tlb_o_set[mmu_idx][i+X86_TLB_PREFD], 1, 0);
#endif
#ifdef X86_TLB_ACOUNT
            ((CPUTLBStatsEntry*) (X86_CPU_GET_TLB_STATS(&env->tlb_o_set[mmu_idx][i])))->acount = 0;
#endif
            env->tlb_o_set[mmu_idx][i] = s_cputlb_empty_entry;
#endif

#if X86_TLB_ASSOC == 4 
#ifdef X86_TLB_PREFTCH
            __builtin_prefetch(&env->tlb_t_set[mmu_idx][i+X86_TLB_PREFD], 1, 0);
            __builtin_prefetch(&env->tlb_f_set[mmu_idx][i+X86_TLB_PREFD], 1, 0);
#endif
#ifdef X86_TLB_ACOUNT
            ((CPUTLBStatsEntry*) (X86_CPU_GET_TLB_STATS(&env->tlb_t_set[mmu_idx][i])))->acount = 0;
            ((CPUTLBStatsEntry*) (X86_CPU_GET_TLB_STATS(&env->tlb_f_set[mmu_idx][i])))->acount = 0;
#endif
            env->tlb_t_set[mmu_idx][i] = s_cputlb_empty_entry;
            env->tlb_f_set[mmu_idx][i] = s_cputlb_empty_entry;
#endif
            // env->tlb_zero ++;
        }
    }

    /* record end time */
    clock_gettime(CLOCK_MONOTONIC, &tend);
    env->tlb_ftime += ((double)tend.tv_sec - (double)tstart.tv_sec)*1.0e9 + tend.tv_nsec - tstart.tv_nsec;

#ifdef X86_DYNSIZE_TLB
    tlb_reload_size(env);
#endif

#ifdef X86_VICTIM_TLB
    /* zero the victim tlb */
    for (i = 0; i < X86_VTLB_ASSOC; i++) {
        int mmu_idx;
        for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
             env->tlb_v_set[mmu_idx][i] = s_cputlb_empty_entry;
        }
    }
#endif

    memset(env->tb_jmp_cache, 0, TB_JMP_CACHE_SIZE * sizeof (void *));

    env->tlb_flush_addr = -1;
    env->tlb_flush_mask = 0;
    tlb_flush_count++;
}

static inline void tlb_flush_entry(CPUTLBEntry *tlb_entry, target_ulong addr)
{
    if (addr == (tlb_entry->addr_read &
                 (TARGET_PAGE_MASK | TLB_INVALID_MASK)) ||
        addr == (tlb_entry->addr_write &
                 (TARGET_PAGE_MASK | TLB_INVALID_MASK)) ||
        addr == (tlb_entry->addr_code &
                 (TARGET_PAGE_MASK | TLB_INVALID_MASK))) {
        *tlb_entry = s_cputlb_empty_entry;
    }
}

void tlb_flush_page(CPUArchState *env, target_ulong addr)
{
    CPUState *cpu = ENV_GET_CPU(env);
    int i;
    int mmu_idx;

#if defined(DEBUG_TLB)
    printf("tlb_flush_page: " TARGET_FMT_lx "\n", addr);
#endif
    /* Check if we need to flush due to large pages.  */
    if ((addr & env->tlb_flush_mask) == env->tlb_flush_addr) {
#if defined(DEBUG_TLB)
        printf("tlb_flush_page: forced full flush ("
               TARGET_FMT_lx "/" TARGET_FMT_lx ")\n",
               env->tlb_flush_addr, env->tlb_flush_mask);
#endif
        tlb_flush(env, 1);
        return;
    }
    /* must reset current TB so that interrupts cannot modify the
       links while we are modifying them */
    cpu->current_tb = NULL;

    addr &= TARGET_PAGE_MASK;
#ifdef X86_DYNSIZE_TLB
    i = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE_ENV(env) - 1);
#else
    i = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
#endif
    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
        tlb_flush_entry(&env->tlb_z_set[mmu_idx][i], addr);
#if X86_TLB_ASSOC >= 2
        tlb_flush_entry(&env->tlb_o_set[mmu_idx][i], addr);
#endif
#if X86_TLB_ASSOC == 4
        tlb_flush_entry(&env->tlb_t_set[mmu_idx][i], addr);
        tlb_flush_entry(&env->tlb_f_set[mmu_idx][i], addr);
#endif
    }

#ifdef X86_VICTIM_TLB
    /* check whether there are entries that need to be flushed in the vtlb */
    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
        int i = 0;
        for (; i < X86_VTLB_ASSOC; i++) {
             tlb_flush_entry(&env->tlb_v_set[mmu_idx][i], addr);
        }
    }
#endif

    tb_flush_jmp_cache(env, addr);
}

/* update the TLBs so that writes to code in the virtual page 'addr'
   can be detected */
void tlb_protect_code(ram_addr_t ram_addr)
{
    cpu_physical_memory_reset_dirty(ram_addr,
                                    ram_addr + TARGET_PAGE_SIZE,
                                    CODE_DIRTY_FLAG);
}

/* update the TLB so that writes in physical page 'phys_addr' are no longer
   tested for self modifying code */
void tlb_unprotect_code_phys(CPUArchState *env, ram_addr_t ram_addr,
                             target_ulong vaddr)
{
    cpu_physical_memory_set_dirty_flags(ram_addr, CODE_DIRTY_FLAG);
}

static bool tlb_is_dirty_ram(CPUTLBEntry *tlbe)
{
    return (tlbe->addr_write & (TLB_INVALID_MASK|TLB_MMIO|TLB_NOTDIRTY)) == 0;
}

void tlb_reset_dirty_range(CPUTLBEntry *tlb_entry, uintptr_t start,
                           uintptr_t length)
{
    uintptr_t addr;

    if (tlb_is_dirty_ram(tlb_entry)) {
        addr = (tlb_entry->addr_write & TARGET_PAGE_MASK) + tlb_entry->addend;
        if ((addr - start) < length) {
            tlb_entry->addr_write |= TLB_NOTDIRTY;
        }
    }
}

static inline ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
{
    ram_addr_t ram_addr;

    if (qemu_ram_addr_from_host(ptr, &ram_addr) == NULL) {
        fprintf(stderr, "Bad ram pointer %p\n", ptr);
        abort();
    }
    return ram_addr;
}

void cpu_tlb_reset_dirty_all(ram_addr_t start1, ram_addr_t length)
{
    CPUState *cpu;
    CPUArchState *env;

    CPU_FOREACH(cpu) {
        int mmu_idx;
        env = cpu->env_ptr;
        for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
            unsigned int i;

#ifdef X86_DYNSIZE_TLB
            for (i = 0; i < CPU_TLB_SIZE_ENV(env); i++) {
#else
            for (i = 0; i < CPU_TLB_SIZE; i++) {
#endif
                tlb_reset_dirty_range(&env->tlb_z_set[mmu_idx][i],
                                      start1, length);
#if X86_TLB_ASSOC == 2
                tlb_reset_dirty_range(&env->tlb_o_set[mmu_idx][i],
                                      start1, length);
#elif X86_TLB_ASSOC == 4
                tlb_reset_dirty_range(&env->tlb_o_set[mmu_idx][i],
                                      start1, length);
                tlb_reset_dirty_range(&env->tlb_t_set[mmu_idx][i],
                                      start1, length);
                tlb_reset_dirty_range(&env->tlb_f_set[mmu_idx][i],
                                      start1, length);
#endif
            }
        }

#ifdef X86_VICTIM_TLB
        for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
            int i = 0;
            for (i = 0; i < X86_VTLB_ASSOC; i++) {
                tlb_reset_dirty_range(&env->tlb_v_set[mmu_idx][i],
                                      start1, length);
            }
        }
#endif
    }
}

static inline void tlb_set_dirty1(CPUTLBEntry *tlb_entry, target_ulong vaddr)
{
    if (tlb_entry->addr_write == (vaddr | TLB_NOTDIRTY)) {
        tlb_entry->addr_write = vaddr;
    }
}

/* update the TLB corresponding to virtual page vaddr
   so that it is no longer dirty */
void tlb_set_dirty(CPUArchState *env, target_ulong vaddr)
{
    int i;
    int mmu_idx;

    vaddr &= TARGET_PAGE_MASK;
#ifdef X86_DYNSIZE_TLB
    i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE_ENV(env) - 1);
#else
    i = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
#endif
    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
        tlb_set_dirty1(&env->tlb_z_set[mmu_idx][i], vaddr);
#if X86_TLB_ASSOC == 2
        tlb_set_dirty1(&env->tlb_o_set[mmu_idx][i], vaddr);
#elif X86_TLB_ASSOC == 4
        tlb_set_dirty1(&env->tlb_o_set[mmu_idx][i], vaddr);
        tlb_set_dirty1(&env->tlb_t_set[mmu_idx][i], vaddr);
        tlb_set_dirty1(&env->tlb_f_set[mmu_idx][i], vaddr);
#endif
    }

#ifdef X86_VICTIM_TLB
    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
        int i = 0;
        for (i = 0; i < X86_VTLB_ASSOC; i++) {
            tlb_set_dirty1(&env->tlb_v_set[mmu_idx][i], vaddr);
        }
    }
#endif
}

/* Our TLB does not support large pages, so remember the area covered by
   large pages and trigger a full TLB flush if these are invalidated.  */
static void tlb_add_large_page(CPUArchState *env, target_ulong vaddr,
                               target_ulong size)
{
    target_ulong mask = ~(size - 1);

    if (env->tlb_flush_addr == (target_ulong)-1) {
        env->tlb_flush_addr = vaddr & mask;
        env->tlb_flush_mask = mask;
        return;
    }
    /* Extend the existing region to include the new page.
       This is a compromise between unnecessary flushes and the cost
       of maintaining a full variable size TLB.  */
    mask &= env->tlb_flush_mask;
    while (((env->tlb_flush_addr ^ vaddr) & mask) != 0) {
        mask <<= 1;
    }
    env->tlb_flush_addr &= mask;
    env->tlb_flush_mask = mask;
}

/* Add a new TLB entry. At most one entry for a given virtual address
   is permitted. Only a single TARGET_PAGE_SIZE region is mapped, the
   supplied size is only used by tlb_flush_page.  */
void tlb_set_page(CPUArchState *env, target_ulong vaddr,
                  hwaddr paddr, int prot,
                  int mmu_idx, target_ulong size)
{
    MemoryRegionSection *section;
    unsigned int index;
    target_ulong address;
    target_ulong code_address;
    uintptr_t addend;
    CPUTLBEntry *te = NULL;
    hwaddr iotlb, xlat, sz;

    assert(size >= TARGET_PAGE_SIZE);
    if (size != TARGET_PAGE_SIZE) {
        tlb_add_large_page(env, vaddr, size);
    }

    sz = size;
    section = address_space_translate_for_iotlb(&address_space_memory, paddr,
                                                &xlat, &sz);
    assert(sz >= TARGET_PAGE_SIZE);

#if defined(DEBUG_TLB)
    printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x" TARGET_FMT_plx
           " prot=%x idx=%d\n",
           vaddr, paddr, prot, mmu_idx);
#endif

    address = vaddr;
    if (!memory_region_is_ram(section->mr) && !memory_region_is_romd(section->mr)) {
        /* IO memory case */
        address |= TLB_MMIO;
        addend = 0;
    } else {
        /* TLB_MMIO for rom/romd handled below */
        addend = (uintptr_t)memory_region_get_ram_ptr(section->mr) + xlat;
    }

    code_address = address;
    iotlb = memory_region_section_get_iotlb(env, section, vaddr, paddr, xlat,
                                            prot, &address);

#ifdef X86_DYNSIZE_TLB
    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE_ENV(env) - 1);
#else
    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
#endif

#if X86_TLB_ASSOC == 4 
    /* try to find an empty tlb, if not default to primary */
    CPUTLBEntry *pte = &env->tlb_z_set[mmu_idx][index];
    CPUTLBEntry *ste = &env->tlb_o_set[mmu_idx][index];
    CPUTLBEntry *tte = &env->tlb_t_set[mmu_idx][index];
    CPUTLBEntry *fte = &env->tlb_f_set[mmu_idx][index];
    if (is_empty_tlb(pte)) {
       te = pte;
       env->iotlb_z_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (is_empty_tlb(ste)) {
       te = ste;
       env->iotlb_o_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (is_empty_tlb(tte)) {
       te = tte;
       env->iotlb_t_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (is_empty_tlb(fte)) {
       te = fte;
       env->iotlb_f_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (!te) {
       te = pte;
#ifdef X86_VICTIM_TLB
       /* evict into a random victim tlb */
       unsigned rindex = rand()%X86_VTLB_ASSOC;
       env->tlb_v_set[mmu_idx][rindex].addr_read  = te->addr_read;
       env->tlb_v_set[mmu_idx][rindex].addr_write = te->addr_write;
       env->tlb_v_set[mmu_idx][rindex].addr_code  = te->addr_code;
       env->tlb_v_set[mmu_idx][rindex].addend     = te->addend;
       env->iotlb_v_set[mmu_idx][rindex] = env->iotlb_z_set[mmu_idx][index];
#endif
       env->iotlb_z_set[mmu_idx][index] = iotlb - vaddr;
    }
#elif X86_TLB_ASSOC == 2 
    /* try to find an empty tlb, if not default to primary */
    CPUTLBEntry *pte = &env->tlb_z_set[mmu_idx][index];
    CPUTLBEntry *ste = &env->tlb_o_set[mmu_idx][index];
    if (is_empty_tlb(pte)) {
       te = pte;
       env->iotlb_z_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (is_empty_tlb(ste)) {
       te = ste;
       env->iotlb_o_set[mmu_idx][index] = iotlb - vaddr;
    }
    if (!te) {
       te = pte;
#ifdef X86_VICTIM_TLB
       /* evict into a random victim tlb */
       unsigned rindex = rand()%X86_VTLB_ASSOC;
       env->tlb_v_set[mmu_idx][rindex].addr_read  = te->addr_read;
       env->tlb_v_set[mmu_idx][rindex].addr_write = te->addr_write;
       env->tlb_v_set[mmu_idx][rindex].addr_code  = te->addr_code;
       env->tlb_v_set[mmu_idx][rindex].addend     = te->addend;
       env->iotlb_v_set[mmu_idx][rindex] = env->iotlb_z_set[mmu_idx][index];
#endif
       env->iotlb_z_set[mmu_idx][index] = iotlb - vaddr;
    }
#else 
    te = &env->tlb_z_set[mmu_idx][index];
    if (is_empty_tlb(te)) env->tlb_load[mmu_idx] ++;
    else env->tlb_cftm ++;
#ifdef X86_VICTIM_TLB
       /* evict into a random victim tlb */
       unsigned rindex = rand()%X86_VTLB_ASSOC;
       env->tlb_v_set[mmu_idx][rindex].addr_read  = te->addr_read;
       env->tlb_v_set[mmu_idx][rindex].addr_write = te->addr_write;
       env->tlb_v_set[mmu_idx][rindex].addr_code  = te->addr_code;
       env->tlb_v_set[mmu_idx][rindex].addend     = te->addend;
       env->iotlb_v_set[mmu_idx][rindex] = env->iotlb_z_set[mmu_idx][index];
#endif
    env->iotlb_z_set[mmu_idx][index] = iotlb - vaddr;
#endif
    te->addend = addend - vaddr;
    if (prot & PAGE_READ) {
        te->addr_read = address;
    } else {
        te->addr_read = -1;
    }

    if (prot & PAGE_EXEC) {
        te->addr_code = code_address;
    } else {
        te->addr_code = -1;
    }
    if (prot & PAGE_WRITE) {
        if ((memory_region_is_ram(section->mr) && section->readonly)
            || memory_region_is_romd(section->mr)) {
            /* Write access calls the I/O callback.  */
            te->addr_write = address | TLB_MMIO;
        } else if (memory_region_is_ram(section->mr)
                   && !cpu_physical_memory_is_dirty(section->mr->ram_addr + xlat)) {
            te->addr_write = address | TLB_NOTDIRTY;
        } else {
            te->addr_write = address;
        }
    } else {
        te->addr_write = -1;
    }

#ifdef X86_TLB_ACOUNT
    /* reorder tlb based on frequency */
    reorder_tlb(env, mmu_idx, index);
#endif
}

/* NOTE: this function can trigger an exception */
/* NOTE2: the returned address is not exactly the physical address: it
 * is actually a ram_addr_t (in system mode; the user mode emulation
 * version of this function returns a guest virtual address).
 */
tb_page_addr_t get_page_addr_code(CPUArchState *env1, target_ulong addr)
{
    /* called when the the code page needs to be accessed, i.e. when
     * the code generator is generating code or before the code is
     * executed. 
     */
    int mmu_idx, page_index, pd=0;
    void *p = NULL;
    MemoryRegion *mr;

#ifdef X86_DYNSIZE_TLB
    page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE_ENV(env1) - 1);
#else
    page_index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
#endif
    mmu_idx = cpu_mmu_index(env1);

#ifdef X86_VICTIM_TLB
    /* try to refill from the victim tlb before checking the regular tlb */
    bool     vtlb = false;
    unsigned vidx = 0;
    for(;vidx < X86_VTLB_ASSOC; ++vidx) {
       vtlb = (env1->tlb_v_set[mmu_idx][vidx].addr_code ==
              (addr & TARGET_PAGE_MASK));
       /* found entry in victim tlb */
       if (vtlb) break; 
    }
#endif

#if X86_TLB_ASSOC == 4 
    bool ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    bool stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    bool ttlb = (env1->tlb_t_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    bool ftlb = (env1->tlb_f_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    if (unlikely(ptlb && stlb && ttlb && ftlb)) {
              cpu_ldub_code(env1, addr);
    }
#elif X86_TLB_ASSOC == 2
    bool ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    bool stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
                (addr & TARGET_PAGE_MASK));
    if (unlikely(ptlb && stlb)) {
              cpu_ldub_code(env1, addr);
    }
#else
    if (unlikely(env1->tlb_z_set[mmu_idx][page_index].addr_code !=
                 (addr & TARGET_PAGE_MASK))) {
              cpu_ldub_code(env1, addr);
    }
#endif

#if X86_TLB_ASSOC == 4 
    ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    ttlb = (env1->tlb_t_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    ftlb = (env1->tlb_f_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    if (!ptlb) pd = env1->iotlb_z_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
    if (!stlb) pd = env1->iotlb_o_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
    if (!ttlb) pd = env1->iotlb_t_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
    if (!ftlb) pd = env1->iotlb_f_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
#elif X86_TLB_ASSOC == 2
    ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    if (!ptlb) pd = env1->iotlb_z_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
    if (!stlb) pd = env1->iotlb_o_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
#else
    pd = env1->iotlb_z_set[mmu_idx][page_index] & ~TARGET_PAGE_MASK;
#endif
    mr = iotlb_t_seto_region(pd);
    if (memory_region_is_unassigned(mr)) {
        CPUState *cpu = ENV_GET_CPU(env1);
        CPUClass *cc = CPU_GET_CLASS(cpu);

        if (cc->do_unassigned_access) {
            cc->do_unassigned_access(cpu, addr, false, true, 0, 4);
        } else {
            cpu_abort(env1, "Trying to execute code outside RAM or ROM at 0x"
                      TARGET_FMT_lx "\n", addr);
        }
    }

#if X86_TLB_ASSOC == 4 
    ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    ttlb = (env1->tlb_t_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    ftlb = (env1->tlb_f_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    if (!ptlb) p = (void *)((uintptr_t)addr + env1->tlb_z_set[mmu_idx][page_index].addend);
    if (!stlb) p = (void *)((uintptr_t)addr + env1->tlb_o_set[mmu_idx][page_index].addend);
    if (!ttlb) p = (void *)((uintptr_t)addr + env1->tlb_t_set[mmu_idx][page_index].addend);
    if (!ftlb) p = (void *)((uintptr_t)addr + env1->tlb_f_set[mmu_idx][page_index].addend);
#elif X86_TLB_ASSOC == 2
    ptlb = (env1->tlb_z_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    stlb = (env1->tlb_o_set[mmu_idx][page_index].addr_code !=
           (addr & TARGET_PAGE_MASK));
    if (!ptlb) p = (void *)((uintptr_t)addr + env1->tlb_z_set[mmu_idx][page_index].addend);
    if (!stlb) p = (void *)((uintptr_t)addr + env1->tlb_o_set[mmu_idx][page_index].addend);
#else
    p = (void *)((uintptr_t)addr + env1->tlb_z_set[mmu_idx][page_index].addend);
#endif
    return qemu_ram_addr_from_host_nofail(p);
}

#define MMUSUFFIX _cmmu
#undef GETPC
#define GETPC() ((uintptr_t)0)
#define SOFTMMU_CODE_ACCESS

#define SHIFT 0
#include "exec/softmmu_template.h"

#define SHIFT 1
#include "exec/softmmu_template.h"

#define SHIFT 2
#include "exec/softmmu_template.h"

#define SHIFT 3
#include "exec/softmmu_template.h"

#undef env
